﻿using System;
using System.Collections.Generic;
using Algoritmia.Utils;

namespace Algoritmia.SemiRings
{
    public interface IIdempotentSemiRing<TItem,in TWeight> : ISemiRing<TItem,TWeight>
    {
    }

    public interface IIdempotentSemiRing<T> : IIdempotentSemiRing<T,T>
    {
    }

    public static class IdempotentSemiRingsExtensions
    {
        public static T1 ArgSum<T1,T2>(this IIdempotentSemiRing<T1,T2> semiRing, IEnumerable<T1> items, Func<T1,T1> fn)
        {
            var equalityComparison = AlgoritmiaFactory.GetDefaultEqualityComparison<T1>();

            T1 result = semiRing.Zero;
            T1 arg = default(T1);
            bool isEmpty = true;
            foreach(var item in items)
            {
                var r = fn(item);
                result = semiRing.Plus(result, r);
                if ( equalityComparison(result,r) )
                {
                    arg = result;
                    isEmpty = false;
                }
            }

            if (isEmpty)
            {
                throw new InvalidOperationException("Sequence contains no matching element");
            }
            return arg;
        }
    }
}
